package edu.umn.msse.farside.FourH.web;

import edu.umn.msse.farside.FourH.domain.Volunteer;
import edu.umn.msse.farside.FourH.services.VolunteerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpSession;

/**
 * Created by IntelliJ IDEA.
 * User: corcutt
 * Date: Mar 17, 2009
 * Time: 6:32:14 PM
 * To change this template use File | Settings | File Templates.
 */
@Controller
@RequestMapping("/login")
public class LoginController
{
    public VolunteerService volunteerService;

    @Autowired
    public void setVolunteerService(VolunteerService volunteerService)
    {
        this.volunteerService = volunteerService;
    }

    @RequestMapping(method = RequestMethod.GET)
    public String loginVolunteerForm(Model model)
    {
        Volunteer volunteer = new Volunteer();
        model.addAttribute("volunteer", volunteer);
        return "login";
    }

    @RequestMapping(method = RequestMethod.POST)
    public String loginVolunteer(@ModelAttribute(value="volunteer") Volunteer volunteer, Model model, HttpSession session)
    {
        if(volunteerService.authenticate(volunteer.getEmail(), volunteer.getPassword())) {
            Volunteer authenticatedVolunteer = volunteerService.findVolunteer(volunteer.getEmail());
            // now that user is set, set the user object in the session
            // caution, this could cause some problems with what spring is doing
            session.setAttribute("volunteer", authenticatedVolunteer);
            // Set the user
            return "redirect:futureEvents";
        }   else {
            // Set the error
            model.addAttribute("error", "Login Failed");

            return "login";
        }
    }
    
}
